package com.lty.practice;

import com.github.pagehelper.PageInfo;
import com.lty.practice.model.Coffee;
import com.lty.practice.service.CoffeeService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

@Slf4j
@EnableTransactionManagement
@SpringBootApplication
@MapperScan("com.lty.practice.mapper")
@EnableCaching(proxyTargetClass = true)
public class PracticeApplication implements ApplicationRunner {
	@Autowired
	private CoffeeService coffeeService;

	public static void main(String[] args) {
		SpringApplication.run(PracticeApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {

		Long[] ids = new Long[]{1L,2L,3L,4L,5L};
		PageInfo<Coffee> pageInfo = coffeeService.selectPage(ids, 2, 2);
		log.info("PageInfo {}", pageInfo);

		log.info("Reading from cache.");
		pageInfo = coffeeService.selectPage(ids, 2, 2);
		log.info("Reading from cache.");
		pageInfo = coffeeService.selectPage(ids, 2, 2);
		log.info("Reading from cache.");
		pageInfo = coffeeService.selectPage(ids, 2, 2);
		log.info("PageInfo {}", pageInfo);

		Coffee c = Coffee.builder().name("espresso")
				.price(Money.of(CurrencyUnit.of("CNY"), 20.0))
				.createTime(new Date())
				.build();
		log.info("Insert {}", c);
		coffeeService.insert(c);
		log.info("After insert {}", c);

		c.setPrice(Money.of(CurrencyUnit.of("CNY"), 30.0));
		c.setUpdateTime(new Date());
		log.info("Update {}", c);
		coffeeService.update(c);
		log.info("After update {}", coffeeService.selectOneById(c.getId()));

		log.info("Delete {}", c);
		coffeeService.delete(c.getId());
		log.info("After delete {}", coffeeService.selectOneById(c.getId()));
		
	}
}
